<script lang="ts" setup>
  import { reactive, ref, watch } from "vue"
  import { request } from "@/utils/service"
  import { carGetList, carGetDetails,carDeleteById } from "@/api/vehicle/vehicle"
  import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
  import { usePagination } from "@/hooks/usePagination"
  import { cloneDeep } from "lodash-es"
  import handle from './components/handle.vue'
  import handledetails from './components/handledetails.vue'

  import useTable from '@/hooks/useTable'

  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
  const dialogVisible = ref<boolean>(false)
  const activeRow = ref<any>()
  const tableData = ref<any>([])
  const searchFormRef = ref<FormInstance | null>(null)
  const searchData = reactive<any>({})

  const dialogDetailsVisible = ref<boolean>(false)

  const getTableData = () => {
    loading.value = true
    carGetList({
      ...paginationData,
      ...searchData
    }).then((res: any) => {
      paginationData.total = res.totalCount
      tableData.value = res.data
    }).catch(() => {
      tableData.value = []
    }).finally(() => {
      loading.value = false
    })
  }

  const { handleSelectionChange, handleBatchDelete, handleDelete,changeIsEnable,handleExport,handleoneDelete } = useTable({getList:getTableData})

  //关闭操作框
  const closeHandle = () => {
    dialogVisible.value = false
  }

  //操作完成
  const successHandle = () => {
    dialogVisible.value = false
    handleSearch()
  }

  //更新操作按钮
  const handleUpdate = (row: any) => {
    activeRow.value = cloneDeep(row)
    // carGetDetails({id:row.carId}).then((res: any) => {
    //   activeRow.value = res
    // }).catch(() => {

    // }).finally(() => {
    //   loading.value = false
    // })
    dialogVisible.value = true
  }

  //新增操作按钮
  const handleAdd = () => {
    activeRow.value = {}
    dialogVisible.value = true
  }

  // 删除
  const handleDel = (row: any)=>{

  }
  // 查看详情
  const handleDeatils = (row: any)=>{
    activeRow.value = cloneDeep(row)
    // carGetDetails({id:row.carId}).then((res: any) => {
    //   activeRow.value = res
    // }).catch(() => {

    // }).finally(() => {
    //   loading.value = false
    // })
    dialogDetailsVisible.value = true
  }

  const successHandle1 =()=>{
  dialogDetailsVisible.value = false
}

const closeHandle1=()=>{
  dialogDetailsVisible.value = false
}

  //搜索操作
  const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  }

  //重置搜索表单
  const resetSearch = () => {
    searchFormRef.value?.resetFields()
    handleSearch()
  }
  watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

//上传文件之前先判断该文件是否是Excel文件
// 文件上传之前判断
const beforeUPload = (file: any) => {
	const isExcel =
		file.type === 'application/vnd.ms-excel' ||
		file.type ===
		'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
	const isLt2M = file.size / 1024 / 1024 < 20;
	if (!isExcel)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件只能是 xls / xlsx 格式！',
			type: 'warning',
		});
	if (!isLt2M)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件大小不能超过 20MB!',
			type: 'warning',
		});
	return isExcel && isLt2M;
};
// 文件数超出提示
const exceedFile = () => {
	ElMessage.warning('最多只能上传一个文件！');
};
// 上传错误提示
const handleError = () => {
	ElMessage.error('导入数据失败，请您重新上传！');
};

//上传成功提示
const handleSuccess = () => {
	ElMessage.success('导入数据成功！');
  getTableData()
};
// 文件上传
const uploadExcel = async (param: any) => {
	let fileFormData = new FormData();
	fileFormData.append('file', param.file);
	//导入公用人事考勤数据
	await request({//这里的http就是普通的axios实例
		method: 'post',
		url: 'bg/car/importCar',
		headers: { "Content-Type": "multipart/form-data" },
		data: fileFormData
	})
};
</script>

<template>
  <div class="app-container">
    <div class="title-wrapper">车辆管理</div>
    <div class="page-main">
      <div shadow="never" class="search-wrapper" v-permission="['vehicle-search']">
        <div class="search-main">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="carNo" label="车牌号">
              <el-input v-model="searchData.carNo" placeholder="请输入车牌号" clearable/>
            </el-form-item>
            <el-form-item prop="customName" label="客户">
              <el-input v-model="searchData.customName" placeholder="请输入客户" clearable/>
            </el-form-item>
            <el-form-item prop="companyName" label="公司">
              <el-input v-model="searchData.companyName" placeholder="请输入公司" clearable/>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>

      <div class="toolbar-wrapper">
        <el-button type="primary" style="margin-right:10px" v-permission="['vehiclemanage-add']"  @click="handleAdd">新增</el-button>
        <el-upload v-permission="['vehiclemanage-import']" action="#" class="upload-demo" accept=".xlsx, .xls" :on-exceed="exceedFile" :on-error="handleError"
          :on-success="handleSuccess" :http-request="uploadExcel" :before-upload="beforeUPload" :show-file-list="true"
          :limit="1">
          <el-button type="primary">导入</el-button>
        </el-upload>
        <!-- 没加权限 -->
        <el-button type="primary" style="margin-left:10px"  v-permission="['vehiclemanage-export']"  @click="handleExport({...paginationData,...searchData}, '/bg/car/exportCarData','车辆导出')">导出</el-button>
        <el-button type="primary" v-permission="['vehiclemanage-export-template']" @click="handleExport({}, '/bg/car/downloadImportTemplate','车辆导入模板')">下载导入模版</el-button>
      </div>
      <div v-loading="loading"  class="table-wrapper">
        <el-table :data="tableData" >
          <!-- <el-table-column sortable prop="carId" label="编号"  /> -->
          <el-table-column type="index" width="60" label="编号"  />
          <el-table-column sortable prop="carNo" label="车牌号"  />
          <el-table-column sortable prop="adminName" label="负责人"  />
          <el-table-column sortable prop="parentName" label="负责人上司"  />
          <el-table-column sortable prop="customNames" label="查看客户"  />
          <el-table-column sortable prop="companyName" label="所属公司" />
          <!-- <el-table-column sortable label="图片" >
            <template #default="scope">
              <div v-if="scope.row.pic">
                <el-image
                  v-for="(image, index) in scope.row.pic.split(',')"
                  :key="index"
                  style="width: 50px; height: 50px; margin-right: 5px;"
                  :src="image"
                  :preview-src-list="scope.row.pic.split(',')"
                />
              </div>
            </template>
          </el-table-column> -->
          <el-table-column sortable prop="type" label="车辆类型"  />
          <el-table-column sortable prop="annualReviewExpires" label="年审到期日"  />
          <el-table-column sortable prop="insuranceReviewExpires" label="保险到期日"  />
          <el-table-column sortable prop="status" label="状态"  />
          <el-table-column fixed="right" label="操作"  >
            <template #default="scope">
              <el-button type="primary" v-permission="['vehiclemanage-edit']" text size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <!-- <el-button type="primary" v-permission="['vehiclemanage-del']" text size="small" @click="handleoneDelete(carDeleteById, scope.row.carMaintenanceId,`${scope.row.carNo}的车辆数据`)">删除</el-button> -->
              <el-button type="primary" v-permission="['vehiclemanage-detail']" text size="small" @click="handleDeatils(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <handle
    v-if="dialogVisible"
    :id="activeRow.carId"
    @success="successHandle"
    @cancel="closeHandle"
    />
    <handledetails
    v-if="dialogDetailsVisible"
    :title="'车辆详情'"
    :id="activeRow.carId"
    @success="successHandle1"
    @cancel="closeHandle1"
    />
</template>

<style lang="scss" scoped>
:deep(.el-upload-list) {
  display: none;

}
</style>
